package dyyx.index;

import java.io.File;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;

import dyyx.CommUtil;
import dyyx.file.FileHandler;
import dyyx.file.ScanContext;

public class IndexHandler implements FileHandler {

	private IndexWriter writer;

	public IndexHandler(IndexWriter writer) {
		this.writer = writer;
	}

	public void run(File file, ScanContext context) throws Exception {
		if (!file.getName().endsWith(".txt")) {
			return;
		}
		// System.out.println(file.getAbsolutePath());
		String filePath = file.getAbsolutePath();

		try {
			String text = CommUtil.readString(file, null);

			Document doc = new Document();

			doc.add(new StringField("path", filePath, Field.Store.YES));

			doc.add(new TextField("content", text, Field.Store.YES));

			// updateResult = writer.addDocument(doc);

			Term delTerm = new Term("path", filePath);

			writer.updateDocument(delTerm, doc);

			System.out.println("index done," + file);

		} catch (Throwable e) {
			System.out.println("index error," + e + "," + filePath);
		}

	}

}
